package org.longteng.mobileluck.orc.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.longteng.mobileluck.orc.service.ImageToTextApiCount;
import org.longteng.mobileluck.orc.vo.OrcApiCount;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * orc的API调用统计基础实现，默认基础类是到ConcurrentHashMap，可扩展保存到DB或redis
 * @author hymn.com
 */
@Slf4j
public class ImageToTextApiCountBase implements ImageToTextApiCount {
    private final ConcurrentHashMap<String,OrcApiCount> orcApiCountMap = new ConcurrentHashMap<>();
    private final SimpleDateFormat sumMonthDateFormat = new SimpleDateFormat("yyyy-MM");

    /**
     * 返回orc的API调用统计状态
     *
     * @param apiType
     * @return
     */
    @Override
    public OrcApiCount getOrcApiCount(String apiType) {
        OrcApiCount orcApiCount = orcApiCountMap.get(apiType);
        if (orcApiCount == null) {
            orcApiCount = new OrcApiCount();
            orcApiCount.setTypeName(apiType);
            orcApiCount.setCurrSumMonth(sumMonthDateFormat.format(new Date()));
            orcApiCountMap.put(apiType, orcApiCount);
        } else {
            String sumMonthStr = sumMonthDateFormat.format(new Date());
            /* 若Str1按字典顺序小于参数字符串Str2，则返回值小于0;Str1按字典顺序大于参数字符串Str2，则返回值大于0
               这样就是换新一个月，次数重新0计算
            */
            if (sumMonthStr.compareTo(orcApiCount.getCurrSumMonth()) > 0 ) {
                log.debug("原来计算月{}已换当前新月{}，就是换新一个月，【{}】ORC次数重新0计算。"
                        , orcApiCount.getCurrSumMonth(), sumMonthStr, apiType);
                orcApiCount.setPreSumMonth(orcApiCount.getCurrSumMonth());
                orcApiCount.setCurrSumMonth(sumMonthStr);
                orcApiCount.setBaseCount(0);
                orcApiCount.setGeneralCount(0);
            } else {
                orcApiCount.setCurrSumMonth(sumMonthStr);
            }

        }

        return orcApiCount;
    }

    /**
     * 更新orc的API调用次数到DB或redis，默认基础类是到ConcurrentHashMap
     *
     * @param orcApiCount
     */
    @Override
    public void updateOrcApiCount(OrcApiCount orcApiCount) {
        if(orcApiCount != null) {
            String apiType = orcApiCount.getTypeName();
            orcApiCountMap.put(apiType, orcApiCount);
        } else {
            log.warn("更新orc的API调用次数失败，更新对象为null。");
        }
    }
}
